#!/usr/bin/perl -w
use strict;
use Getopt::Long;
use lib "/net/cpp-group/Leo/bin";
#88888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Usage

#88888888888888888888888888888888888888888888888888888888888888888888888888888888
my $usage = <<'USAGE';

USAGE:

    split_lines.pl
							--path
                            [--every_nth_line 100]
                            [--help]
                            [--verbose]
                            file


        This script takes files supplied via STDIN or the command line
		and splits them up into different files each with N lines

		The output files are specified on path and an incremental number will be
		added to the file name before the last dot
USAGE

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Get options

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
# mandatory


# optional parameters
my $help = undef;
my $verbose = undef;
my $path;
my $line = 100;
GetOptions('help' => \$help,
		   'verbose' => \$verbose,
		   'path=s' => \$path,
		   'every_nth_line=s' => \$line,

		   );

die $usage if ($help);
die $usage unless $path;


my ($path_part, $extension) = ($path, "");
if ($path =~ /(.*)(\..*)/)
{
	($path_part, $extension) = ($1, $2);
}

sub open_file_with_indexed_name
{
	my ($file_cnt, $path_part, $extension) = @_;
	my $file_num = '0' x (5 - length($file_cnt)) . $file_cnt;
	my $file_name = ">".$path_part.$file_num.$extension;
	open $_[3], $file_name or die "Error\n\tCould not open $file_name\n$!";

}

# file index
my $file_cnt;

# file handle
my $fh;

# lines in current file
my $line_cnt;

# whether any file is open. To prevent orphaned empty file at end
my $file_open = 0;

#count progress dots
my $dots = 0;
if ($verbose)
{
	print STDERR "\n\tSplitting files...\n";
}

while (<>)
{
	#
	# print after opening file if necessary
	#
	if (!$file_open)
	{
		unless ($dots)
		{
			print STDERR "\t[" if $verbose;
		}
		$dots++;
		print STDERR "\n\t" if ($dots % 50 == 0) and $verbose;
		print STDERR '.' if $verbose;
		++$file_cnt;
		open_file_with_indexed_name($file_cnt, $path_part, $extension, $fh);
		$file_open++;
		$line_cnt = 0;
	}
	print $fh $_;
	++$line_cnt;


	if ($line_cnt >= $line)
	{
		close $fh;
		$file_open = 0;
	}
}
if ($dots and $verbose)
{
	print STDERR "]\n";
	print STDERR "\tSplit into $dots files each with $line lines\n\n";
}
close $fh;



